import { request } from '../../request/index'
import { requestPayment, showToast } from '../../utils/asyncWX'
Page({
  data: {
    address: {},
    cart: [],
    totalNum: 0,
    totalPrice: 0
  },
  onShow() {
    const address = wx.getStorageSync('address')
    let cart = wx.getStorageSync('cart')
    cart = cart.filter(item => item.isChecked)
    const totalNum = cart.length
    let totalPrice = 0
    cart.forEach(item => totalPrice += item.num * item.goods_price)
    this.setData({
      address,
      cart,
      totalNum,
      totalPrice
    })
  },
  // 支付
  async handelPay() {
    try {
      const token = wx.getStorageSync('token')
      const { cart } = this.data
      let goods = []
      cart.forEach(item => goods.push({
        goods_id: item.goods_id,
        goods_number: item.num,
        goods_price: item.goods_price
      }))
      // 获取token(没有获取到5555)
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/index'
        })
        return
      }
      // 创建订单
      const { order_number } = await request({
        url: '/my/orders/create',
        method: 'POST',
        data: {
          order_price: this.data.totalPrice,
          consignee_addr: this.data.address,
          goods
        }
      })
      // 发起预支付
      const { pay } = await request({
        url: '/my/orders/req_unifiedorder',
        method: 'POST',
        data: {
          order_number
        }
      })
      // 微信支付
      await requestPayment(pay)
      // 查询订单状态
      const res = await request({
        url: '/my/orders/chkOrder',
        method: 'POST',
        data: {
          order_number
        }
      })
      await showToast({title: '支付成功'})
      // 删除缓存中已支付的商品
      const newCart = wx.getStorageSync('cart')
      newCart = newCart.filter(item => !item.checked)
      wx.setStorageSync('cart', newCart)
      // 跳转订单页面
      wx.navigateTo({
        url: '/pages/order/index'
      })
    } catch (error) {
      await showToast({title: '支付失败'})
    }
  }
})
/*
1 创建订单
  1 先获取用户登录成功后的token
    1 获取encryptedData, iv, rawData, signature, code
    2 token 只有企业id才能获取
  2 获取订单编号
    1 请求头 token
    2 order_number
2 准备预支付
  1 发送请求获取pay参数
3 发起微信支付
  1 requestPayment(pay)
4 查询订单
  1 查询订单支付状态
  2 查询历史订单
 */